<?php

namespace Remoteshell\PhpBotSdk\threads;

use parallel\Runtime;
use parallel\Future;

class ThreadPool
{
    private $pool = [];
    private $maxThreads;

    public function __construct(int $maxThreads)
    {
        $this->maxThreads = $maxThreads;
    }

    public function addTask(callable $task): Future
    {
        while (count($this->pool) >= $this->maxThreads) {
            $this->wait();
        }

        $runtime = new Runtime();
        $future = $runtime->run(function () use ($task) {
            return $task();
        });

        $this->pool[] = [
            'runtime' => $runtime,
            'future' => $future,
        ];

        return $future;
    }

    public function wait(): void
    {
        foreach ($this->pool as $index => $thread) {
            if ($thread['future']->done()) {
                unset($this->pool[$index]);
            }
        }

        $this->pool = array_values($this->pool);
    }

    public function shutdown(): void
    {
        while (!empty($this->pool)) {
            $this->wait();
        }
    }
}
